package com.erp.ae.utils;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.ae.domain.enums.AliExpressInterfaceEnum;
import com.global.iop.api.IopClient;
import com.global.iop.api.IopClientImpl;
import com.global.iop.api.IopRequest;
import com.global.iop.api.IopResponse;
import com.global.iop.domain.Protocol;
import com.global.iop.util.ApiException;
import com.global.iop.util.FileItem;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.utils.RedisUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringEscapeUtils;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Duration;
import java.util.Map;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class AeApiUtils {

    private static String ACCESS_TOKEN_KEY = "access_token_key:";
    private static String url = "https://api-sg.aliexpress.com";
    private static String appkey = "500890";
    private static String appSecret = "IEu1gaoOSF1TrrXBwXKBiM39i23gvQzW";
//	private static String appkey = "501176";
//	private static String appSecret = "dsZ9gceLuJ8VrAPpLz23X0sSfGhsO4Hf";

    public static String auth(Long storeId, String code) {
        String responseBody = null;
        if (StringUtils.isNotEmpty(code)) {

            // 获取access_token
            IopClient client = new IopClientImpl(url, appkey, appSecret);
            IopRequest request = new IopRequest();
            request.setApiName(AliExpressInterfaceEnum.token.getCode());
            request.addApiParameter("code", code);
            IopResponse response = null;
            try {
                response = client.execute(request, Protocol.GOP);
                responseBody = response.getBody();
                System.out.println(responseBody);
                Dict body = JsonUtils.parseMap(responseBody);

                // 保存redis
                RedisUtils.setCacheObject(ACCESS_TOKEN_KEY + storeId, responseBody,
                        Duration.ofSeconds(body.getLong("expires_in")));
            } catch (ApiException e) {
                e.printStackTrace();
            }
        }
        return responseBody;

    }

    /**
     * 根据code生成access_token
     *
     * @date 2023年3月17日
     */
    public static String getToken(String storeId) {

        if (storeId == null)
            return null;

        String access_token = null;
        String responseBody = null;
        Object cacheObject = RedisUtils.getCacheObject(ACCESS_TOKEN_KEY + storeId);
        // 获取redis有无

        if (ObjectUtils.isNotEmpty(cacheObject)) {
//            System.out.println("*************cacheObject:" + cacheObject.toString());
//            JSONObject jsonObject = JSONObject.parseObject(str);
            responseBody = cacheObject.toString();
//            System.out.println(responseBody);
            Dict body = JsonUtils.parseMap(responseBody);
            access_token = body.getStr("access_token");
            if (StringUtils.isEmpty(access_token)) {
                throw new NullPointerException("店铺(" + storeId + ")授权可能过期，请查验");
            } else {
                return access_token;
            }
        } else {
            throw new NullPointerException("未查到该店铺:" + storeId + "授权");
        }
    }

    public static String getToken(Long storeId) {
        return getToken(storeId.toString());

    }

    /**
     * request.addApiParameter版
     *
     * @param apiName
     * @param apiParameterMap
     * @param protocolType
     */
    public static String sendRequest(String apiName, Map<String, Object> apiParameterMap, Protocol protocolType,
                                     String accessToken) {
        IopClient client = new IopClientImpl(url, appkey, appSecret);
        IopRequest request = new IopRequest();
        request.setApiName(apiName);
        // 循环填入
        for (String key : apiParameterMap.keySet()) {
            request.addApiParameter(key, apiParameterMap.get(key).toString());
        }
        IopResponse response = null;
        System.out.println(request.getApiParams());
        try {
            response = client.execute(request, accessToken, protocolType);
            Thread.sleep(10);
        } catch (ApiException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return response.getBody();
    }

    /**
     * 参数传Json字符串版 参数为Map
     *
     * @param apiName
     * @param parametName
     * @param apiParameterMap
     * @param type
     * @param accessToken
     * @return
     */
    public static String sendRequest(String apiName, String parametName, Map<String, Object> apiParameterMap,
                                     Protocol type, String accessToken) {
        IopClient client = new IopClientImpl(url, appkey, appSecret);
        IopRequest request = new IopRequest();
        request.setApiName(apiName);

        JSONObject mapJson = new JSONObject(apiParameterMap);

        request.addApiParameter(parametName, mapJson.toJSONString());

        IopResponse response = null;
        try {
            response = client.execute(request, accessToken, type);
            System.out.println(response.getBody());
            System.out.println("-----------------------------");
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return response.getBody();
    }

    /**
     * 参数传Json字符串版 参数为String
     *
     * @param apiName
     * @param parametName
     * @param parameterStr
     * @param type
     * @param accessToken
     * @return
     */
    public static String sendRequest(String apiName, String parametName, String parameterStr, Protocol type,
                                     String accessToken) {
        IopClient client = new IopClientImpl(url, appkey, appSecret);
        IopRequest request = new IopRequest();
        request.setApiName(apiName);
        if (!parametName.equals("")) {
            request.addApiParameter(parametName, parameterStr);
        }
        IopResponse response = null;
        try {
            response = client.execute(request, accessToken, type);
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        System.out.println(response.getBody());
        return response.getBody();
    }

    public static String getchildrenpostcategorybyid(String param0) {
        IopClient client = new IopClientImpl(url, appkey, appSecret);
        IopRequest request = new IopRequest();
        request.setApiName("aliexpress.category.redefining.getchildrenpostcategorybyid");
        request.addApiParameter("param0", param0);
        IopResponse response = null;
        try {
            response = client.execute(request, Protocol.TOP);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return response.getBody();
    }

    public static String getsizetemplatesbycategoryid(String leafCategoryId) {
        IopClient client = new IopClientImpl(url, appkey, appSecret);
        IopRequest request = new IopRequest();
        request.setApiName("aliexpress.offer.redefining.getsizetemplatesbycategoryid");
        request.addApiParameter("leaf_category_id", leafCategoryId);
        request.addApiParameter("current_page", "1");
        IopResponse response = null;
        try {
            response = client.execute(request, "", Protocol.TOP);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        System.out.println(response.getBody());
        return response.getBody();
    }

    public static String getchildattributesresultbypostcateidandpath(String param1, Long storeId) {
        IopClient client = new IopClientImpl(url, appkey, appSecret);
        IopRequest request = new IopRequest();
        request.setApiName("aliexpress.category.redefining.getchildattributesresultbypostcateidandpath");
        request.addApiParameter("param1", param1);
        IopResponse response = null;
        try {
            String token = getToken(storeId);
            response = client.execute(request, token, Protocol.TOP);
            System.out.println(response.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return response.getBody();
    }

    /**
     * 无参版
     *
     * @param apiName
     * @param protocolType
     * @param accessToken
     * @return
     */
    public static String sendRequest(String apiName, Protocol protocolType, String accessToken) {
        IopClient client = new IopClientImpl(url, appkey, appSecret);
        IopRequest request = new IopRequest();
        request.setApiName(apiName);
        IopResponse response = null;
        try {
            response = client.execute(request, accessToken, protocolType);
            System.out.println(response.getBody());
            Thread.sleep(10);
        } catch (ApiException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return response.getBody();
    }

    public static String sendImageRequest(Integer isAddWatemark, String storeUserName, String imageUrl, String groupId, String accessToken) {
        IopClient client = new IopClientImpl(url, appkey, appSecret);
        IopRequest request = new IopRequest();
        request.setApiName("aliexpress.photobank.redefining.uploadimageforsdk");
        if (groupId != null) {
            request.addApiParameter("group_id", groupId);
        }
//		request.addFileParameter("image_bytes",new FileItem(imageUrl));
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(imageUrl).openConnection();
            connection.setConnectTimeout(10 * 1000);
            InputStream inputStream = connection.getInputStream();

            //调用工具类，生成新的MD5(待测试)
//			InputStream inputStreamNew = ImageMD5ModifierUtils.update(inputStream);
            InputStream inputStreamNew = null;

            if (ObjectUtils.isNotNull(isAddWatemark) && isAddWatemark == 1) {
                //确认加水印
                // 用加水印的方式代替新MD5， TODO 店铺名称需要动态传递
                try {
                    inputStreamNew =
                            ImageAddWatermarkUtils.addWatermark(imageUrl,
                                    storeUserName.substring(0, 12));
                } catch (Exception e) {
                    inputStreamNew = inputStream;
                }
            } else {
                inputStreamNew = inputStream;
            }


            String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
            request.addFileParameter("image_bytes", new FileItem(fileName, inputStreamNew));
            request.addApiParameter("file_name", fileName);
            IopResponse response = null;
            System.out.println(request.getApiParams());
            response = client.execute(request, accessToken, Protocol.TOP);
            Thread.sleep(10);
            System.out.println(response.getBody());
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String sendRequestHttpMethodIsGet(String apiName, Map<String, Object> paremeterMap, Protocol top,
                                                    String accessToken) {
        IopClient client = new IopClientImpl(url, appkey, appSecret);
        IopRequest request = new IopRequest();
        request.setApiName(apiName);
        request.setHttpMethod("GET");
        // 循环填入
        for (String key : paremeterMap.keySet()) {
            request.addApiParameter(key, paremeterMap.get(key).toString());
        }
        IopResponse response = null;
        try {
            response = client.execute(request, accessToken, Protocol.TOP);
            System.out.println(response.getBody());
            Thread.sleep(10);
        } catch (ApiException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return response.getBody();
    }

    public static String sendRequestHttpMethodIsGet(String apiName, Protocol top, String accessToken) {
        IopClient client = new IopClientImpl(url, appkey, appSecret);
        IopRequest request = new IopRequest();
        request.setApiName(apiName);
        request.setHttpMethod("GET");
        IopResponse response = null;
        try {
            response = client.execute(request, accessToken, Protocol.TOP);
            System.out.println(response.getBody());
            Thread.sleep(10);
        } catch (ApiException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return response.getBody();
    }

    public static void main(String[] args) {
        String code = "3_500890_XYIXrvgU7CjxYx4pNU4xrNmk1444";
        String responseBody = null;
        if (StringUtils.isNotEmpty(code)) {

            // 获取access_token
            IopClient client = new IopClientImpl(url, appkey, appSecret);
            IopRequest request = new IopRequest();
            request.setApiName("/auth/token/create");
            request.addApiParameter("code", code);
            IopResponse response = null;
            try {
                response = client.execute(request, Protocol.GOP);
                responseBody = response.getBody();
                System.out.println(responseBody);
            } catch (ApiException e) {
                e.printStackTrace();
            }
        }
        IopClient client = new IopClientImpl(url, appkey, appSecret);
        IopRequest request = new IopRequest();
        request.setApiName("aliexpress.freight.redefining.calculatefreight");
        request.addApiParameter("height", "1");
        request.addApiParameter("weight", "1");
        request.addApiParameter("pack_add_weight", "1");
        request.addApiParameter("count", "1");
        request.addApiParameter("freight_template_id", "1000");
        request.addApiParameter("pack_add_unit", "1");
        request.addApiParameter("is_custom_pack_weight", "false");
        request.addApiParameter("width", "1");
        request.addApiParameter("length", "1");
        request.addApiParameter("product_price", "{\"amount\":\"100.01\",\"cent\":\"10000\",\"currency_code\":\"USD\"}");
        request.addApiParameter("pack_base_unit", "1");
        request.addApiParameter("country", "RU");

        IopResponse response = null;
        try {
            System.out.println(request.getApiParams());
            response = client.execute(request, "50000700228zETSmacQNFS8mEuVtpe92otdLwZxS1d1aa56el8GEuiN0wiG8x7VmjQEh",
                    Protocol.TOP);
            System.out.println(response.getBody());
            System.out.println(JSONObject.parseObject(response.getBody())
                    .getJSONObject("cainiao_global_handover_cloudprint_get_response").getJSONObject("result")
                    .getJSONObject("data").getJSONObject("print_data").getString("encryptedData"));

            Thread.sleep(10);
        } catch (Exception e) {
            e.printStackTrace();
        }

//		String body = getchildattributesresultbypostcateidandpath("200001619");
//		System.out.println(body);

//		String body = getchildattributesresultbypostcateidandpath("200001619");
//		System.out.println(body);
    }

    public static String setToken(String res, Long id) {
        String tokenValue = JSONObject.toJSONString(res);
        System.out.println(tokenValue);
        JSONObject jsonObject = JSONObject.parseObject(res);

        RedisUtils.setCacheObject(ACCESS_TOKEN_KEY + id, jsonObject.toJSONString());
        Object cacheObject = RedisUtils.getCacheObject(ACCESS_TOKEN_KEY + id);
        // 获取redis有无
        String responseBody = cacheObject.toString();
        System.out.println(responseBody);
        return null;
    }
}
